
export default class Utils {
    private static _instance: Utils;
    public static get Instance(): Utils {
        this._instance = this._instance || new Utils();
        return this._instance;
    }

    //不改变位置的情况下修改节点的父节点
    public changeParentNode(target: cc.Node, newPar: cc.Node) {
        let v1 = target.convertToWorldSpaceAR(cc.v2(0, 0));
        let v2 = newPar.convertToNodeSpaceAR(v1);
        target.parent = newPar;
        target.setPosition(v2);
    }

    /**
     * 返回当前年月日
     */
    public getNowData() {
        let time = new Date();
        let year = time.getFullYear();
        let month = time.getMonth() + 1;
        let day = time.getDate();
        return [year, month, day];
    }

    // 获取正整数
    public getRandomInt(min: number, max: number) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }

    public loadSingleRes(url: string, type: any, callback?: Function) {
        return new Promise((resolve: (value: unknown) => void, reject: (reason?: any) => void) => {
            cc.resources.load(url, type, (err, res) => {
                if (err) {
                    console.error(`load ${url} is err`);
                    resolve(null);
                    if (callback) callback(null);
                } else {
                    resolve(res);
                    if (callback) callback(res);
                }
            })
        })
    }

    /**
     * 给按钮绑定组件并添加回调函数
     * @param btnNode 按钮所在节点
     * @param target 脚本所绑定的节点
     * @param component  脚本的名称
     * @param handler   脚本中函数的名称
     * @param customEventData 回调函数的自定义参数
     */
    public addCallbackToButton(btnNode: cc.Node, target: cc.Node, component: string, handler: string, customEventData: string = "") {
        const transition = cc.Button.Transition.SCALE;
        const duration = 0.1;
        const zoomScale = 0.9;
        const enableAutoGrayEffect = true;
        const interactable = true;
        let clickEventHandler = new cc.Component.EventHandler();
        clickEventHandler.target = target;
        clickEventHandler.component = component;
        clickEventHandler.handler = handler;
        clickEventHandler.customEventData = customEventData;

        let btn = btnNode.getComponent(cc.Button);
        if (!btn) btn = btnNode.addComponent(cc.Button);
        btn.transition = transition;
        btn.duration = duration;
        btn.zoomScale = zoomScale;
        btn.enableAutoGrayEffect = enableAutoGrayEffect;
        btn.interactable = interactable;
        btn.clickEvents.push(clickEventHandler);
    }
}
